/*
 //  JSONDownloader.m
 //  TextDownloader
 //
 //  Created by Brennan Stehling on 10/25/09.
 //  Copyright 2009 SmallSharpTools LLC. All rights reserved.
 */

#import "JSONDownloader.h"
#import "TextDownloader.h"
#import "CJSONDeserializer.h"

@implementation JSONDownloader

#pragma mark - Properties

@synthesize delegate		= _delegate;

#pragma mark - Memory Management

- (void) dealloc {
	[self.delegate release];
	[super dealloc];
}

#pragma mark - Public

- (void)downloadJSON:(NSString *)urlString delegate:(id)delegate {
	self.delegate = delegate;
	
	TextDownloader *td = [[TextDownloader alloc] init];
	td.supportedContentTypes = [NSArray arrayWithObjects:
								@"application/json", 
								@"application/x-json",
								@"text/json", nil];
	[td downloadText:urlString delegate:self];
	[td release];
}

#pragma mark - TextDownloader delegate methods

- (void) downloadTextFinished: (NSString *) text {	
	NSData *jsonData;
	
	// Does the data look like an array? Array values must be wrapped as a JS object.
	NSRange range = [text rangeOfString:@"["];
	if (range.location == 0){
		jsonData = [[NSString stringWithFormat:@"{ \"json\" : %@}", text] 
					dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	}
	else {
		jsonData = [text dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	}
	
	// Use TouchJSON to populate the data and dictionary
	NSError *error = nil;
	NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
	
	if (error) {
		NSString *errorMessage = [NSString stringWithFormat: 
								  @"An error occurred while parsing the JSON string: %@", error];		
		
		// call the parsingJSONFailed:errorMessage: (callback)
		if([[self delegate] respondsToSelector:@selector(parsingJSONFailed:)]) {
			[[self delegate] parsingJSONFailed:errorMessage];
		}
	}
	else {
		// call the downloadJSONFinished delegate (callback)
		if([[self delegate] respondsToSelector:@selector(downloadJSONFinished:)]) {
			[[self delegate] downloadJSONFinished:dictionary];
		}
	}
}

- (void) downloadTextFailed: (NSString *) errorMessage {	
	if (errorMessage != nil) {
		// report that the download failed
		if([[self delegate] respondsToSelector:@selector(downloadJSONFailed:)]) {
			[[self delegate] downloadJSONFailed:errorMessage];
		}
	}
}

@end
